package com.bw.demoseckill.service.impl;

import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.demoseckill.entity.TbGoods;
import com.bw.demoseckill.entity.TbOrder;
import com.bw.demoseckill.entity.TbUser;
import com.bw.demoseckill.mapper.GoodsMapper;
import com.bw.demoseckill.mapper.OrderMapper;
import com.bw.demoseckill.mapper.UserMapper;
import com.bw.demoseckill.service.GoodsService;
import com.bw.demoseckill.service.UserService;
import com.bw.demoseckill.utils.ConstUtils;
import com.bw.demoseckill.utils.JwtTokenUtils;
import com.bw.demoseckill.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;



    @Override
    public ResponseResult addGoods(TbGoods tbGoods) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //检查工作人员是否存在
        TbGoods goods= goodsMapper.selectOne(new QueryWrapper<TbGoods>()
                .eq("goods_name",tbGoods.getGoodsName())
                .last("limit 1"));

        //工作人员已存在
        if (goods!=null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("工作人员已存在");
            return result;
        }

        goods = new TbGoods();

        goods.setGoodsName(tbGoods.getGoodsName());
        goods.setStatus(0);
        goods.setTitle(tbGoods.getTitle());
        goods.setStartTime(new Date());
        goods.setEndTime(new Date());
        goods.setXprice(tbGoods.getXprice());
        goods.setYprice(tbGoods.getYprice());
        goods.setGoodsType(tbGoods.getGoodsType());
        goods.setNum(tbGoods.getNum());

        //添加
        goodsMapper.insert(goods);
        resultMap.put("goods",goods);
        return result;
    }

    @Override
    public ResponseResult doBeginGrab(Integer userId) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 检查优惠信息
        TbGoods goods = goodsMapper.selectOne(
                new QueryWrapper<TbGoods>()
                        .eq("status", 1)
                        .orderByDesc("start_time")
                        .last("limit 1")
        );
        if(goods == null) {
            return result;
        }

        //--2 生产优惠券，放入redis
        // 循环加入优惠券
        for (int idx = 0; idx < goods.getNum(); idx++) {
            redisTemplate.opsForList().leftPush(ConstUtils.WAITTING_COUPON_KEY, goods.getId());
        }
        // 设置优惠券的过期时间
        redisTemplate.expire(ConstUtils.WAITTING_COUPON_KEY, 1, TimeUnit.HOURS);

        // 设置以抢到优惠券用户集合的时间
        redisTemplate.expire(ConstUtils.CATCH_COUPON_KEY, 1, TimeUnit.HOURS);

        //--3 修改优惠活动的状态
        goods.setStatus(2);
        goodsMapper.updateById(goods);

        //
        System.out.println("开始抢购了");
        return result;
    }

    @Override
    public ResponseResult grabClass(Integer id) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 判断用户在不在
        TbUser user = userMapper.selectById(id);
        if(user == null) {
            result.setFailMessage("学生不存在");
            return result;
        }

        //-- 2 判断有没有商品可以抢
        // waiting-coupon
        if(!redisTemplate.hasKey(ConstUtils.WAITTING_COUPON_KEY)) {
            result.setFailMessage("请您稍后再试");
            return result;
        }
        else {
            Long size = redisTemplate.opsForList().size(ConstUtils.WAITTING_COUPON_KEY);
            if(size <= 0) {
                result.setFailMessage("亲，您的手速慢了。欢迎下次再来！");
                return result;
            }
        }

        //--3 是否已经抢过了
        if(redisTemplate.opsForSet().isMember(ConstUtils.CATCH_COUPON_KEY, id)) {
            result.setFailMessage("亲，您已经抢过了。欢迎下次再来！");
            return result;
        }

        //--4 终于开始抢了
        Integer gid = (Integer) redisTemplate.opsForList().rightPop(ConstUtils.WAITTING_COUPON_KEY);
        if(gid == null) {
            result.setFailMessage("亲，您的手速慢了。欢迎下次再来！");
            return result;
        }

        redisTemplate.opsForSet().add(ConstUtils.CATCH_COUPON_KEY, id);

        // 给rabbitmq发送消息
        TbOrder tbOrder= new TbOrder();
        tbOrder.setUid(id);
        tbOrder.setGid(gid);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 7);
        String strNowDate = simpleDateFormat.format(c.getTime());

        orderMapper.insert(tbOrder);
        String content = "<h1>抢购成功</h1>";
        MailUtil.send("1102845646@qq.com", "抢购成功", content, true);

        //--5 提示抢购完成（提示成功，失败）
        //result.setFailMessage("亲，您的手速慢了。欢迎下次再来！");
        return result;
    }

    @Override
    public ResponseResult goodsList() {
        ResponseResult result = ResponseResult.SUCCESS();
        List<TbGoods> list = goodsMapper.selectList(new QueryWrapper<TbGoods>()
                .eq("status",0));
        result.setResult(list);
        return result;
    }
}
